﻿using System;
using System.Collections.Specialized;
using System.Configuration;
using System.Drawing;
using System.Windows.Forms;
using Microsoft.Win32;
using Microsoft.WindowsAPICodePack.Taskbar;
using Slippor.Douban.Radio.RadioAssist;

namespace Slippor.Douban.Radio
{
    public partial class Main : Form
    {
        private static readonly String _defaultTitle = "豆瓣电台";
        private readonly String _autoRunPath = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Run";

        private Timer _timer = new Timer();
        private RadioState _currentState = RadioState.Minimized;
        private IntPtr _mainHandle = IntPtr.Zero;
        private String _title = _defaultTitle;
        private bool _taskBarBuilt = false;
        private Point _originalLocation = new Point(100, 100);

        public Main()
        {
            InitializeComponent();
            Shown += Main_Shown;
            Closed += Main_Closed;
            webBrowserDouban.DocumentTitleChanged += WbDoubanDocumentTitleChanged;
            _timer.Tick += new EventHandler(timer_Tick);
            //SizeChanged += new EventHandler(Main_SizeChanged); 
            InitialProperties();
            //SHDocVw.WebBrowser wb = (SHDocVw.WebBrowser)wbDouban.ActiveXInstance;
        }

        private void Main_SizeChanged(object sender, EventArgs e)
        {
            switch(WindowState)
            {
                case FormWindowState.Minimized:
                    if (_currentState == RadioState.Minimized)
                    {
                        WindowState = FormWindowState.Normal;
                        _currentState = RadioState.Normal;
                        Location.Offset(_originalLocation);
                    }
                    else
                    {
                        WindowState = FormWindowState.Normal;
                        _currentState = RadioState.Minimized;
                        _originalLocation = Location;
                        Location = new Point(-32000, -32000);
                    }
                    break;
                case FormWindowState.Normal:
                    break;
            }
        }

        private void InitialProperties()
        {
            NameValueCollection apps = ConfigurationManager.AppSettings;
            toolStripMenuItemPop.Checked = apps["NotifyPop"] == "1";
            toolStripMenuItemNotify.Checked = apps["AutoNotify"] == "1";

            using(RegistryKey R_local = Registry.LocalMachine)
            using (RegistryKey R_run = R_local.CreateSubKey(_autoRunPath))
            {
                toolStripMenuItemAutoRun.Checked = R_run.GetValue("DoubanRadio") != null;
            }
        }

        private void Main_Shown(object sender, EventArgs e)
        {
            if (toolStripMenuItemNotify.Checked)
            {
                HideToNotify();
            }
            else
            {
                ConfirmTaskBar();
            }
        }

        private void Main_Closed(object sender, EventArgs e)
        {
            //SendMSNMessage(false, "Office", "");
            TabbedThumbnail preview = TaskbarManager.Instance.TabbedThumbnail.GetThumbnailPreview(webBrowserDouban);
            if (preview != null)
            {
                TaskbarManager.Instance.TabbedThumbnail.RemoveThumbnailPreview(preview);
            }
        }

        private void WbDoubanDocumentTitleChanged(object sender, EventArgs e)
        {
            String wbTitle = webBrowserDouban.DocumentTitle;
            if (wbTitle.IndexOf(_defaultTitle) == 0 || wbTitle == "登录豆瓣")
            {
                _title = _defaultTitle;
                _btnSearch.Enabled = false;
                toolStripMenuItemSearch.Enabled = false;
                if(wbTitle == "登录豆瓣")
                {
                    WindowState = FormWindowState.Normal;
                    if (_currentState == RadioState.Notify)
                    {
                        _currentState = RadioState.Normal;
                        ShowFromNotiyfy();
                    }
                }
            }
            else
            {
                //SendMSNMessage(_isPlay, "Music", Text);
                _title = wbTitle.Split('-')[0].Trim();
                _btnSearch.Enabled = true;
                toolStripMenuItemSearch.Enabled = true;
                if (toolStripMenuItemPop.Checked)
                {
                    notifyIcon.ShowBalloonTip(1500, "", _title, ToolTipIcon.Info);
                }
                TrackHistory(_title);
                ConfirmRadioState();
                _timer.Interval = (int)(0.5 * 1000);
                _timer.Start();
            }
            Text = _title;
            notifyIcon.Text = _title;
            toolStripMenuItemTitle.Text = _title;
            if (_title.Length > 10)
            {
                toolStripMenuItemTitle.Text = _title.Substring(0, 10) + "...";
            }
        }

        private void SetFav()
        {
            FavState fav = CheckFav();
            if (fav == FavState.Unknown)
            {
                toolStripMenuItemFav.Text = "收藏/取消";
            }
            else
            {
                if (fav == FavState.取消)
                {
                    _btnFav.Icon = Properties.Resources.Fav;
                    if (_currentHistoryItem != null)
                    {
                        _currentHistoryItem.Image = Properties.Resources.Fav1;
                    }
                }
                else
                {
                    _btnFav.Icon = Properties.Resources.UnFav;
                    if(_currentHistoryItem != null)
                    {
                        _currentHistoryItem.Image = Properties.Resources.UnFav1;
                    }
                }
                _btnFav.Tooltip = fav.ToString();
                toolStripMenuItemFav.Text = fav.ToString();
                TaskbarManager.Instance.SetOverlayIcon(Handle, Properties.Resources.Fav, fav.ToString());
            }
        }

        #region 记录历史
        private int index = 0;
        private ToolStripMenuItem _currentHistoryItem = null;
        private void TrackHistory(String title)
        {
            if(_currentHistoryItem != null)
            {
                _currentHistoryItem.BackColor = Color.Transparent;
            }
            ToolStripMenuItem historyItem = new ToolStripMenuItem(String.Format(" {2} {1}. {0}", title, ++index, DateTime.Now.ToShortTimeString()));
            historyItem.Tag = title;
            historyItem.BackColor = Color.LightSkyBlue;
            historyItem.ToolTipText = "点击复制歌名";
            _currentHistoryItem = historyItem;
            historyItem.Click += new EventHandler(historyItem_Click);
            toolStripMenuItemHistory.DropDownItems.Insert(0, historyItem);
        }

        private void historyItem_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem toolStripMenuItem = sender as ToolStripMenuItem;
            Clipboard.SetText(toolStripMenuItem.Tag.ToString());
        }
        #endregion

        private void timer_Tick(object sender, EventArgs e)
        {
            _timer.Stop();
            SetFav();
            if (_currentState != RadioState.Notify)
            {
                TaskbarManager.Instance.TabbedThumbnail.SetThumbnailClip(Handle, new Rectangle(34, 34, 120, 120));
                if (_currentState == RadioState.TempNormal)
                {
                    _currentState = RadioState.Minimized;
                    WindowState = FormWindowState.Minimized;
                }
            }
            else if (Visible)
            {
                HideToNotify();
            }
        }

        #region 任务栏状态按钮
        private ThumbnailToolbarButton _btnFav = new ThumbnailToolbarButton(Properties.Resources.UnFav, "收藏");
        private ThumbnailToolbarButton _btnDel = new ThumbnailToolbarButton(Properties.Resources.Del, "去除");
        private ThumbnailToolbarButton _btnNext = new ThumbnailToolbarButton(Properties.Resources.Next, "跳过");
        private ThumbnailToolbarButton _btnSearch = new ThumbnailToolbarButton(Properties.Resources.Search, "搜索");
        private ThumbnailToolbarButton _btnControl = new ThumbnailToolbarButton(Properties.Resources.Shut, "停止");
        private ThumbnailToolbarButton _btnNotify = new ThumbnailToolbarButton(Properties.Resources.Notify, "任务栏");
        private bool _isPlay = true;

        private void CreateTaskbar()
        {
            _btnControl.Click += btn_Click;
            _btnDel.Click += btn_Click;
            _btnFav.Click += btn_Click;
            _btnNext.Click += btn_Click;
            _btnSearch.Click += _btnSearch_Click;
            _btnNotify.Click += _btnNotify_Click;

            TaskbarManager.Instance.ThumbnailToolbars.AddButtons(Handle, _btnFav, _btnDel, _btnNext, _btnControl, _btnSearch, _btnNotify);
            TaskbarManager.Instance.TabbedThumbnail.SetThumbnailClip(Handle, new Rectangle(34, 34, 120, 120));
            TaskbarManager.Instance.SetOverlayIcon(Handle, Properties.Resources.Play, "播放中");
        }

        private void CreateJumpList()
        {
            JumpList jumpList = JumpList.CreateJumpList();
            jumpList.AddUserTasks(
                new JumpListSeparator(),
                new JumpListLink("http://douban.fm/", "豆瓣电台"), 
                new JumpListLink("http://douban.com/", "豆瓣")) ;
            jumpList.Refresh();
        }

        private void _btnSearch_Click(object sender, ThumbnailButtonClickedEventArgs e)
        {
            SearchUtility.SearchInBaidu(_title);
        }

        private void _btnNotify_Click(object sender, ThumbnailButtonClickedEventArgs e)
        {
            HideToNotify();
        }

        private void btn_Click(object sender, EventArgs e)
        {
            ThumbnailToolbarButton btn = (ThumbnailToolbarButton)sender;
            ICommand command = new OtherCommand();
            if (btn == _btnFav)
            {
                command = new FavCommand();
            }
            else if (btn == _btnDel)
            {
                command = new FavCommand();
            }
            else if (btn == _btnNext)
            {
                command = new NextCommand();
            }
            else if (btn == _btnControl)
            {
                command = new ControlCommand();
            }

            ExcuteCommand(command);
        }

        private void ExcuteCommand(ICommand command)
        {
            switch(command.Command)
            {
                case Command.Del:
                    _currentHistoryItem.Image = Properties.Resources.Del1;
                    break;
                case Command.Next:
                    _currentHistoryItem.Image = Properties.Resources.Next1;
                    break;
                case Command.Control:
                    if (_isPlay)
                    {
                        _btnControl.Icon = Properties.Resources.Play;
                        _btnControl.Tooltip = "播放";
                        toolStripMenuItemControl.Text = "播放";
                        TaskbarManager.Instance.SetOverlayIcon(Handle, Properties.Resources.Shut, "停止中");
                    }
                    else
                    {
                        _btnControl.Icon = Properties.Resources.Shut;
                        _btnControl.Tooltip = "停止";
                        toolStripMenuItemControl.Text = "停止";
                    }
                    _isPlay = _btnNext.Enabled = _btnFav.Enabled = _btnDel.Enabled = !_isPlay;
                    break;
                default:
                    break;
            }
            ConfirmRadioState();
            ConfirmHandler();
            Utility.ControlFlash(_mainHandle, command.X, command.Y);
            if (command.Interval > 0)
            {
                _timer.Interval = command.Interval;
                _timer.Start();
            }
            else
            {
                if (_currentState == RadioState.Minimized)
                {
                    WindowState = FormWindowState.Minimized;
                }
            }
        }
        #endregion

        #region 托盘
        private void HideToNotify()
        {
            _currentState = RadioState.Notify;
            WindowState = FormWindowState.Normal;
            this.Hide();
            this.notifyIcon.Visible = true;
            toolStripMenuItemMinimize.Visible = true;
        }

        private void ShowFromNotiyfy()
        {
            this.Show();
            toolStripMenuItemMinimize.Visible = false;
            WindowState = FormWindowState.Normal;
            if (_currentState == RadioState.Normal)
            {
                TopMost = true;
                TopMost = false;
            } 
            ConfirmTaskBar();
            _timer.Interval = (int)(0.35 * 1000);
            _timer.Start();
        }

        #region 设置
        private void toolStripMenuItemNotify_Click(object sender, EventArgs e)
        {
            Utility.SetConfig("AutoNotify", Convert.ToInt16(toolStripMenuItemNotify.Checked));
        }

        private void toolStripMenuItemPop_Click(object sender, EventArgs e)
        {
            Utility.SetConfig("AutoNotify", Convert.ToInt16(toolStripMenuItemPop.Checked));
        }

        private void toolStripMenuItemAutoRun_Click(object sender, EventArgs e)
        {
            String R_startPath = Application.ExecutablePath;
            using(RegistryKey R_local = Registry.LocalMachine)
            using(RegistryKey R_run = R_local.CreateSubKey(_autoRunPath))
            {
                if (toolStripMenuItemAutoRun.Checked)
                {
                    R_run.SetValue("DoubanRadio", R_startPath);
                }
                else
                {
                    try
                    {
                        R_run.DeleteValue("DoubanRadio", false);
                    }
                    catch (Exception)
                    {
                        MessageBox.Show("您需要管理员权限修改", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        throw;
                    }
                }
            }
        }
        #endregion

        private void toolStripMenuItemFav_Click(object sender, EventArgs e)
        {
            if(_currentState == RadioState.Notify)
            {
                this.Show();
                WindowState = FormWindowState.Normal;
                ConfirmTaskBar();
            }
            if (toolStripMenuItemFav.Text == "收藏/取消")
            {
                SetFav();
                DialogResult result = MessageBox.Show(String.Format("确定{0}?", toolStripMenuItemFav.Text), "收藏", MessageBoxButtons.OKCancel);
                if (result == DialogResult.OK)
                {
                    ExcuteCommand(new FavCommand());
                }
                else
                {
                    this.Hide();
                }
            }
            else
            {
                ExcuteCommand(new FavCommand());
            }
        }

        private void toolStripMenuItemNext_Click(object sender, EventArgs e)
        {
            ExcuteCommand(new NextCommand());
        }

        private void toolStripMenuItemDel_Click(object sender, EventArgs e)
        {
            ExcuteCommand(new DelCommand());
        }

        #region 搜索
        private void toolStripMenuItemBaidu_Click(object sender, EventArgs e)
        {
            SearchUtility.SearchInBaidu(_title);
        }

        private void toolStripMenuItemGoogle_Click(object sender, EventArgs e)
        {
            SearchUtility.SearchInGoogle(_title);
        }

        private void toolStripMenuItemDouban_Click(object sender, EventArgs e)
        {
            SearchUtility.SearchInDouban(_title);
        }

        private void toolStripMenuItemSougou_Click(object sender, EventArgs e)
        {
            SearchUtility.SearchInSougou(_title);
        }

        private void toolStripMenuItemKuwo_Click(object sender, EventArgs e)
        {
            SearchUtility.SearchInKuwo(_title);
        }
        #endregion

        private void toolStripMenuItemControl_Click(object sender, EventArgs e)
        {
            ExcuteCommand(new ControlCommand());
        }

        private void notifyIcon_DoubleClick(object sender, EventArgs e)
        {
            if(_currentState == RadioState.Notify)
            {
                _currentState = RadioState.Normal;
                ShowFromNotiyfy();
            }
            else
            {
                HideToNotify();
            }
        }

        private void toolStripMenuItemMinimize_Click(object sender, EventArgs e)
        {
            _currentState = RadioState.Minimized;
            ShowFromNotiyfy();
        }

        private void toolStripMenuItemClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void toolStripMenuItemTitle_Click(object sender, EventArgs e)
        {
            Clipboard.SetText(_title);
        }
   
        private void toolStripMenuItemRefresh_Click(object sender, EventArgs e)
        {
            webBrowserDouban.Refresh();
        }
        #endregion

        private void ConfirmHandler()
        {
            if (_mainHandle == IntPtr.Zero)
            {
                _mainHandle = Utility.GetHandler(webBrowserDouban.Handle, "Internet Explorer_Server");
            }
        }

        private void ConfirmRadioState()
        {
            if (_currentState != RadioState.Notify && _currentState != RadioState.TempNormal)
            {
                if (WindowState == FormWindowState.Normal)
                {
                    _currentState = RadioState.Normal;
                }
                if (WindowState == FormWindowState.Minimized)
                {
                    WindowState = FormWindowState.Normal;
                    _currentState = RadioState.TempNormal;
                }
            }
        }

        private FavState CheckFav()
        {
            ConfirmHandler();
            IntPtr hwnd = Utility.GetDC(_mainHandle);//对本窗体获取
            if (hwnd != IntPtr.Zero)
            {
                int v = Utility.GetPixel(hwnd, 280, 150);
                Color color = Color.FromArgb(v);
                if (color == null || color.A == 255)
                {
                    return FavState.Unknown;
                }
                else
                {
                    if (color.G < 100)
                    {
                        return FavState.取消;
                    }
                    else
                    {
                        return FavState.收藏;
                    }
                }
            }
            else
            {
                return FavState.Unknown;
            }
        }

        private void ConfirmTaskBar()
        {
            if (!_taskBarBuilt)
            {
                if (TaskbarManager.IsPlatformSupported)
                {
                    CreateTaskbar();
                    CreateJumpList();
                }
                _taskBarBuilt = true;
            }
        }
    }
}